package com.sgb.kjwl.viewmodel.material;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.Toast;

import androidx.core.util.Pair;
import androidx.databinding.ObservableField;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.CompanyDetailsEntity;
import com.sgb.kjwl.model.entity.CompanyStatusEntity;
import com.sgb.kjwl.model.entity.ConcreteDetailEntity;
import com.sgb.kjwl.model.entity.ConcreteParamEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.MaterialCompanyEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.ConcreteEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.MaterialRepertory;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author wangyongyi
 */
public class ConcreteDetailModel extends BaseViewModel {
    public ObservableField<String> shopImAccount = new ObservableField<>("");
    public ObservableField<ConcreteDetailEntity> concreteDetailEntity = new ObservableField<ConcreteDetailEntity>();
    private final MaterialRepertory repertory;
    private ConcreteDetailActivity2 activity;

    public ConcreteDetailModel(ConcreteDetailActivity2 concreteDetailActivity2, MaterialRepertory repertory) {
        activity = concreteDetailActivity2;
        this.repertory = repertory;
    }


    public void getDetail(String id) {
        DialogHelper.showProgressDialog2(activity, null, "获取信息中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsAPI().getConcreteDetail(id).enqueue(new ICallBack<BaseEntity<ConcreteDetailEntity>>() {
            @Override
            public void onSuccess(BaseEntity<ConcreteDetailEntity> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                activity.showProductInfo(data.getData());
                concreteDetailEntity.set(data.getData());
            }
        });
    }

    public void getDetail(String id, String sid, String gid, String serviceId) {
        DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);

        NewAPIManager.getInstance().getGoodsAPI().getConcreteDetail(id, sid, gid, serviceId).enqueue(new ICallBack<BaseEntity<ConcreteDetailEntity>>() {
            @Override
            public void onSuccess(BaseEntity<ConcreteDetailEntity> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                activity.showProductInfo(data.getData());
                concreteDetailEntity.set(data.getData());
            }
        });
    }

    public void getPrice(ConcreteParamEntity data) {
        APIManager.getInstance().getMaterialAPI().getConcretePrice(data).enqueue(new Callback<BaseEntity<ConcreteParamEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<ConcreteParamEntity>> call, Response<BaseEntity<ConcreteParamEntity>> response) {
                if (response.body() == null || !response.body().getState().equals("ok")) return;
                activity.showPrice(response.body().getData().getTotalPrice());
            }

            @Override
            public void onFailure(Call<BaseEntity<ConcreteParamEntity>> call, Throwable t) {

            }
        });
    }

    public void addCart(ConcreteParamEntity data) {
        APIManager.getInstance().getMaterialAPI().addConcreteCart(data).enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {
                if (response.body() == null || !response.body().getState().equals("ok")) {
                    MToast.showToast(activity, "加入采购单失败");
                    return;
                } else {
                    MToast.showToast(activity, response.body().getData());
                    getCarCount();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {

            }
        });
    }

    public void getCarCount() {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getCarCount().enqueue(new Callback<BaseEntity<Integer>>() {
            @Override
            public void onResponse(Call<BaseEntity<Integer>> call, Response<BaseEntity<Integer>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.refreshCarCount(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Integer>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void checkToken(String tag) {
        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            VerificationCodeLoginActivity.start(activity);
            return;
        }

        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getShoppingCarAPI().checkToken().enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if ("shopping_car".equals(tag)) {
                        activity.checkTokenView();
                    } else {
                        activity.addCart();
                    }
                } else {
                    if (!"Miss_Permission".equals(response.body().getCode())) {
                        MToast.showToast(activity, response.body().getMsg());
                        VerificationCodeLoginActivity.start(activity);
                    } else {
                        MToast.showToast(activity, response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCompanyModel(String cid) {
        NewAPIManager.getInstance().getGoodsAPI().getMaterialShopDetail(cid).enqueue(new Callback<BaseEntity<MaterialCompanyEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<MaterialCompanyEntity>> call, @NotNull Response<BaseEntity<MaterialCompanyEntity>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    MToast.showToast(activity, "服务器异常~");
                    return;
                }
                activity.showCompanyInfo(response.body().getData());
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<MaterialCompanyEntity>> call, @NotNull Throwable t) {

            }
        });
    }

    /****
     * 获取供应商的详细信息
     * @param companyId
     */
    public void getCompanyInformation(String companyId) {
        NewAPIManager.getInstance().getMaterialAPI().getGoodsCompanyInfoDetailsFront(companyId).enqueue(new Callback<BaseEntity<CompanyDetailsEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<CompanyDetailsEntity>> call, @NotNull Response<BaseEntity<CompanyDetailsEntity>> response) {
                if (response.body() == null) {
                    return;
                }
                activity.showCompanyInfoDetail(response.body().getData());

            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<CompanyDetailsEntity>> call, @NotNull Throwable t) {
                String error = t.getMessage();
            }
        });
    }

    public void userFocusCompany(String shopId) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().userFocusCompany(shopId).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals("ok")) {
                    activity.setuserFocusCompanyStatus();
                } else {
                    Toast.makeText(activity, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void getuserFocusCompanyStatus(String shopId) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getuserFocusCompanyStatus(shopId).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals("ok")) {
                    activity.setuserFocusCompanyStatus((Boolean) response.body().getData());
                } else {
//                    Toast.makeText(activity, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void getuserFocusStatus(String skuId) {
        DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        Map<String, Object> paramMap = new HashMap<>(1);
        paramMap.put("skuid", skuId);
        NewAPIManager.getInstance().getGoodsAPI().getuserFocusStatus(paramMap).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals("ok")) {
                    activity.setuserFocusCompanyStatus((Boolean) response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void userFocus(String shopId) {
        DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsAPI().userFocus(shopId).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity> call, @NotNull Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if ("ok".equals(response.body().getState())) {
                    activity.setuserFocusStatus();
                } else {
                    Toast.makeText(activity, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void getConcreteList(boolean isLoadMore) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", 1);
        map.put("pageSize", 6);
        map.put("areaCode", repertory.getAreaCode());
        DialogHelper.showProgressDialog(activity, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getConcreteList(map).enqueue(new Callback<BaseEntity<ListResponse<List<ConcreteEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, Response<BaseEntity<ListResponse<List<ConcreteEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getConcreteList(response.body().getData().getList());
                } else {
                    MToast.showToast(activity, response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    /**
     * 获取平台声明的标签
     */
    public void getPlatformStatement() {
        APIManager.getInstance().getGoodsAPI().getPlatformStatement().enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<String>> call, @NotNull Response<BaseEntity<String>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getPlatformStatement(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<String>> call, @NotNull Throwable t) {

            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        }
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Response<BaseEntity<LoginEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response == null || response.body() == null) {
                    return;
                }
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(activity, SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        activity.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
        DialogHelper.dismissProgressDialog();
        SharedPreferenceUtil.getInstance().cleatData();
        saveUserInfo(response.body().getData());
        MToast.showToast(activity, "登录成功");
        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
        getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
//        Preferences.saveUserAccount(loginEntity.getImAccount());
//        Preferences.saveUserToken(loginEntity.getImToken());
    }

    public void getUserInfo() {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<UserMsgEntity>> call, @NotNull Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response == null || response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) {
                    return;
                }
                if (APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    activity.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<UserMsgEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void itemImAlternate(String shopId, Integer type) {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        NewAPIManager.getInstance().getCommonAPI().itemImAlternate(shopId, type).enqueue(new Callback<BaseEntity<EnquiryImAlternateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<EnquiryImAlternateEntity>> call, Response<BaseEntity<EnquiryImAlternateEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().getConfirmType() != null && 2 == response.body().getData().getConfirmType()) {
                        if (!TextUtils.isEmpty(response.body().getData().getConfirmMessage())) {
                            MToast.showToast(activity, response.body().getData().getConfirmMessage());
                        }
                    } else {
                        List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers = response.body().getData().getCompanyCustomers();
                        if (companyCustomers != null) {
                            activity.showImWindow(companyCustomers);
                        }
                    }
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<EnquiryImAlternateEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCompanyStatus(String companyNo, String companyName) {
        if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
            DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        NewAPIManager.getInstance().getGoodsAPI().getCompanyStatus(companyNo).enqueue(new Callback<BaseEntity<CompanyStatusEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<CompanyStatusEntity>> call, Response<BaseEntity<CompanyStatusEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if ("0".equals(response.body().getData().companyStatus)) {
                        activity.checkTokenView();
                    } else {
                        new RoundDialog.Builder(activity)
                                .title("温馨提示")
                                .content("您当前的企业：【" + companyName + "】已被注销")
                                .confirm("知道了")
                                .singleBtn(true)
                                .contentGravity(Gravity.CENTER)
                                .cancelable(true)
                                .show();
                    }
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<CompanyStatusEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    //1.5.7 商品首页询价新增token失效的校验，后端提议用这个接口来判断
    public void getCheckUserInfo() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    activity.buildInquiryReleaseParam();
                } else {
                    MToast.showToast(activity, "登录过期,请重新登录");
                    ActivityJump.startActivity(AppRouteConstant.VerificationCodeLoginActivity, Pair.create("isJump", false));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

}
